import mysql.connector
# 获取连接
from setting import DATABASES
connection=mysql.connector.connect(
    **DATABASES['default']
    #autocommit=True 开启自动提交后，增删改操作无需手动调用connection.commit()
)

# connection = mysql.connector.connect(**{
#         'host': '127.0.0.1',  # 主机ip
#         'user': 'root',  # 用户名
#         'passwd': 'root',  # 用户密码 记得修改
#         'db': 'wsgi_mall',  # 数据库
#         'charset':'utf8',
# })

class Dict2Obj(dict):

    def __getattr__(self, key):
        if key not in self:
            return None
        else:
            value = self[key]
            if isinstance(value,dict):
                value = Dict2Obj(value)
            return value


def select(sql,args=tuple(),key=[]):

    # 获取游标
    cur=connection.cursor()
    # 执行查询语句，无需查询参数
    cur.execute(sql,args)
    result2=cur.fetchall() #获取全部
    # key=['id','username','password','truename','birthday','phone','address','zipcode','balance','create_time']
    res=[]
    for i in result2:
        res.append(Dict2Obj(dict(zip(key,i))))
    connection.commit()
    return res
def update(sql,args=tuple()):
    cur=connection.cursor()
    cur.execute(sql,args)
    # 提交修改
    connection.commit()

def delete(sql,args=tuple()):
    cur=connection.cursor()
    cur.execute(sql,args)
    connection.commit()

def insert(sql,args=tuple()):
    cur=connection.cursor()
    # 执行更新语句，使用占位符,注意参数是元祖形式
    cur.execute(sql,args)
    # 提交修改
    connection.commit()

# if __name__ == '__main__':
#     u1=User("tony",6,12,99)
#     u1.save()
#     u1.filter(name=1,id=1)
#     u1.all()
#     u1.get_one_page()